package com.hoperay.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;

import com.liferay.util.portlet.PortletProps;

public class MaxMindUtil {

	private static final String maxMindLoginId = PortletProps
			.get("max.mind.login.id");

	public static GeoLocation getLocation(String ipAddress) {

		if (ipAddress.equalsIgnoreCase("127.0.0.1")) {
			ipAddress = "203.192.247.50";
		}
		
		String url = "http://geoip3.maxmind.com/b?l=" + maxMindLoginId + "&i="+ ipAddress;

		GeoLocation location = null;
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);

		try {
			client.executeMethod(method);

			InputStream is = method.getResponseBodyAsStream();

			String data = IOUtils.toString(is);

			location = new GeoLocation(data);
			
			is.close();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}

		return location;
	}

	public static void dialNumber(String contactNumber, String generatedPIN) {
		String url = "https://www.maxmind.com/app/telephone_http?l="
				+ maxMindLoginId + "&phone=%2B" + contactNumber
				+ "&verify_code=" + generatedPIN;

		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);

		try {
			client.executeMethod(method);

			InputStream is = method.getResponseBodyAsStream();

			is.close();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	}
}